#!/bin/sh

# Part of Zombie Navigator
# Copyright © 2015  Zombie Navigator Developers

dir="`dirname "$0"`"
dir="`cd "$dir";pwd`"
cd "$dir/src"

buildsDir="$dir/builds"
buildTmpDir="$dir/.build"

mkdir -p "$buildsDir"


# Create .xpi
if ! which jpm >/dev/null 2>&1 ; then
	echo "Please install jpm somewhere in PATH" >&2
	exit 1
fi

cd ..
cp -rf src "$buildTmpDir"
cd "$buildTmpDir"

find . -type f \( -name '*.js' -or -name '*.html' \) -execdir sh -c 'egrep -v "^\s*$|vim:" "$1" > "$1.tmp" && mv -f "$1.tmp" "$1"' -- {} \;

find . -type f -name '*.css' -execdir sh -c 'egrep -v "^\s*$|vim:" "$1" | tr -d "\t\n" | perl -pe "s/\s*([{:>+])\s*/\1/g ; s/;}/}/g" > "$1.tmp" && mv -f "$1.tmp" "$1"' -- {} \;

find . -type f -name '*.json' -execdir sh -c 'egrep -v "^\s*$" "$1" | sed "s/^ *//" | tr -d "\n" > "$1.tmp" && mv -f "$1.tmp" "$1"' -- {} \;
du -a -h --apparent-size --max-depth 3 || du -ahd3


echo "Please ignore JPM warnings about the 'sember' (if any)" >&2
echo "Because we use '~' for prereleases (for consistence with GNU/Linux conventions)" >&2

jpm xpi || {
	echo "[ERROR] JPM: Failed" >&2
	exit 1
}

if which advzip >/dev/null 2>&1 ; then
	# AdvanceCOMP available
	echo "Recompressing..." >&2
	advzip -z -4 -i 200 ./*.xpi
else
	echo "NOTE: Skipping recompression (AdvanceCOMP needed)..." >&2
fi

echo "Saving the archive..." >&2
targetDir="$buildsDir/`date +%s`"
mkdir -p "$targetDir"
mv -b -v ./*.xpi "$targetDir"/ || mv -n -v ./*.xpi "$targetDir"/

cd ..
rm -rf "$buildTmpDir"

echo "Done?" >&2


# vim: ts=4 noet ai

